package com.example.lc.myjurisdictiondemo;

import android.Manifest;
import android.app.Activity;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.Log;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 是否获取到对应的权限
 */
public class Util extends Activity implements EasyPermissions.PermissionCallbacks {
    private String TAG = "lc";
    private Activity act;
    private boolean isJurisdictionOK = false;
    public Util(Activity act) {
        this.act = act;
        initPermission();
    }

    public static final int All_PERMISSION = 1;

    @AfterPermissionGranted(All_PERMISSION)
    private void initPermission() {
        //shouldShoowRequestPermissionRationale,在第一次申请权限时会返回false，意味着第一次不需要告知用户申请该权限的理由，
        //如果第一次申请被拒
        String[] perms = {Manifest.permission.CAMERA};

        // 检查应用程序已经具有所需的权限
        if (EasyPermissions.hasPermissions(act, perms)) {// 有了
            Log.e(TAG, "有了相应的权限了.");
            isJurisdictionOK = true;
        } else {// 还没
            EasyPermissions.requestPermissions(act, "需要获取应用的相关权限",
                    All_PERMISSION, perms);
            isJurisdictionOK = false;
        }

    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        // 某些权限已被授予
        Log.e(TAG, "成功");
        isJurisdictionOK = true;
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        // 某些权限被拒绝
        Log.e(TAG, "失败");
        isJurisdictionOK = false;
        //（可选）检查用户是否拒绝任何权限，并检查“不要再询问”。
        // 这将显示一个对话框，指示他们在应用设置中启用权限。
        if (EasyPermissions.somePermissionPermanentlyDenied(act, perms)) {
            new AppSettingsDialog.Builder(act).setTitle("需要权限").setRationale("某些权限没有授予,继续运行可能会崩溃.").build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            act.onRequestPermissionsResult(requestCode, permissions, grantResults);
            // 将结果转发到EasyPermissions
            EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        }
    }

    public boolean isJurisdictionOK(){
        return isJurisdictionOK;
    }
}
